﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using common;
using System.Globalization;
using System.Resources;
using dao;
using System.Collections;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace GTVAccountingSystem.view.usercontrol
{
    public partial class uclUsersDetailTab : UserControl
    {
        ResourceManager rm = Constant.RM;
        CultureInfo culture = Constant.CULTURE;
        UsersDAO usersDAO = new UsersDAO();
        UserGroupDAO groupDAO = new UserGroupDAO();
        PermissionDAO permissionDAO = new PermissionDAO();
        DataRow row;
        String idUserCurrent = "na";
        DataTable dtUserPermissionDetails = new DataTable();
        int pageIndex = 0;
        public uclUsersDetailTab()
        {
            InitializeComponent();
        }
        public void getDataFromUserInformation(DataRow row)
        {
            if(!idUserCurrent.Equals(row["IDLogin"].ToString()))
            {
                this.row = row;
                if (tabControlUser.SelectedIndex == 0)
                {
                    showDetailsUser(row["IDLogin"].ToString());
                }
                else if (tabControlUser.SelectedIndex == 1)
                {
                    loadAllTabOfTabPermission();
                }
                idUserCurrent = row["IDLogin"].ToString();
            }
        }
        public void showDetailsUser(String idLogin)
        {
            row = usersDAO.getUserByID(idLogin).Rows[0];
            grbUser.Text = rm.GetString("lblUser", culture);
            lblUsername.Text = rm.GetString("lblUsername", culture) + " : " + row["Username"];
            lblStaffCode.Text = rm.GetString("lblStaffCode", culture) + " : " + row["StaffCode"].ToString();
            lblFullName.Text = rm.GetString("lblFullName", culture) + " : " + row["FirstName"];
            //lblLastName.Text = rm.GetString("lblLastName", culture) + " : " + row["LastName"].ToString();
            lblEmail.Text = rm.GetString("lblEmail", culture) + " : " + row["Email"].ToString();
            lblPhone.Text = rm.GetString("lblPhone", culture) + " : " + row["Phone1"];
            if (row["Phone2"] != null && !row["Phone2"].ToString().Equals(""))
                lblPhone.Text += " - " + row["Phone2"].ToString();
            lblAddress.Text = rm.GetString("lblAddress", culture);
            if (!row["Status"].ToString().Equals("0"))
                lblStatus.Text = rm.GetString("lblStatus", culture) + " : " + rm.GetString("statusInUse");
            else
                lblStatus.Text = rm.GetString("lblStatus", culture) + " : " + rm.GetString("statusLock");
            lblCompanyName.Text = rm.GetString("lblCompanyName", culture) + " : " + row["CompanyName"];
            lblCompanyAddress.Text = rm.GetString("lblCompanyAddress", culture) + " : " + row["CompanyAddress"];
            lblCompanyPhone.Text = rm.GetString("lblCompanyPhone", culture) + " : " + row["CompanyPhone1"];
            if (row["CompanyPhone2"] != null && !row["CompanyPhone2"].ToString().Equals(""))
                lblCompanyPhone.Text += " - " + row["CompanyPhone2"].ToString();
            if (row["CompanyPhone3"] != null && !row["CompanyPhone3"].ToString().Equals(""))
                lblCompanyPhone.Text += " - " + row["CompanyPhone3"].ToString();
            lblCompanyFax.Text = rm.GetString("lblCompanyFax", culture) + " : " + row["Fax"].ToString();
            
        }

        private void btnCreateNewUser_Click(object sender, EventArgs e)
        {
            Boolean check = true;
            for (int i = 0; i < Constant.LIST_OPEN.Count; i++)
            {
                Object[] objs = (Object[])Constant.LIST_OPEN[i];
                if (objs[0].ToString().Equals("frmCreateNewUser"))
                {
                    form.frmCreateNewUser createUser = ((form.frmCreateNewUser)objs[1]);
                    createUser.Activate();
                    createUser.WindowState = FormWindowState.Normal;
                    check = false;
                    break;
                }
            }
            if (check)
            {
                form.frmCreateNewUser createUser = new form.frmCreateNewUser();
                createUser.Show();
                Object[] objs = { "frmCreateNewUser", createUser };
                Constant.LIST_OPEN.Add(objs);
            }
        }

        private void btnResetPass_Click(object sender, EventArgs e)
        {
            if (row != null)
            {
                if(MessageBox.Show("Do you really want to reset password of " + row["FirstName"] + "?", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                    if (usersDAO.resetPasswordUserByLoginID(row["IDLogin"].ToString(), row["FirstName"].ToString()))
                    {
                        MessageBox.Show("Password has been reset");
                    }
            }
        }

        private void btnDisableStatusUser_Click(object sender, EventArgs e)
        {
            if (row != null)
            {
                String id = row["IDLogin"].ToString();
                String status = "";
                String action = "";
                if (row["Status"].ToString().Equals("1"))
                {
                    status = "0";
                    action = "lock";
                }
                else
                {
                    status = "1";
                    action = "unlock";
                }
                if (MessageBox.Show("Do you really want to " + action + row["FirstName"] + "?", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    if (usersDAO.lockOrUnlockUserByLoginID(row["IDLogin"].ToString(), status, row["FirstName"].ToString()))
                        MessageBox.Show("User " + action + "ed");
                }
            }
        }
        public void loadListGroup()
        {
            /*DataTable dtUserGroup = groupDAO.getAllUserGroup();
            ltbUserGroup.DataSource = dtUserGroup;
            ltbUserGroup.DisplayMember = "GroupName";
            ltbUserGroup.ValueMember = "ID";*/
        }
        public void loadListUserGroup()
        {
            /*DataTable dtUserGroupDetails = groupDAO.getAllUserGroup();
            ltbUserGroup.DataSource = dtUserGroupDetails;
            ltbUserGroup.DisplayMember = "GroupName";
            ltbUserGroup.ValueMember = "ID";*/
        }
        public void loadTableUserPermissionDetails()
        {    
            dtUserPermissionDetails = usersDAO.getAllUserPermission(row["IDLogin"].ToString(), tabControlPermission.TabPages[tabControlPermission.SelectedIndex].Tag.ToString());
            dgvPermission.DataSource = dtUserPermissionDetails;
            if (dgvPermission.Columns.Count == 0)
            {
                dgvPermission.Columns.Add((DataGridViewTextBoxColumn)createColumnForDataGridView(rm.GetString("lblFunctionName", culture), "Textbox", "FunctionName"));
                dgvPermission.Columns.Add((DataGridViewCheckBoxColumn)createColumnForDataGridView(rm.GetString("lblView", culture), "Checkbox", "Pread"));
                dgvPermission.Columns.Add((DataGridViewCheckBoxColumn)createColumnForDataGridView(rm.GetString("lblAdd", culture), "Checkbox", "PWrite"));
                dgvPermission.Columns.Add((DataGridViewCheckBoxColumn)createColumnForDataGridView(rm.GetString("lblUpdate", culture), "Checkbox", "PEdit"));
                dgvPermission.Columns.Add((DataGridViewCheckBoxColumn)createColumnForDataGridView(rm.GetString("lblDelete", culture), "Checkbox", "PDelete"));
            }
        }
        public Object createColumnForDataGridView(String headerName, String type, String propertyName)
        {
            if (type.Equals("Checkbox"))
            {
                DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
                col.HeaderText = headerName;
                DataGridViewCheckBoxCell cell = new DataGridViewCheckBoxCell();
                cell.TrueValue = "1";
                cell.FalseValue = "0";
                col.CellTemplate = cell;
                col.DataPropertyName = propertyName;
                return col;
            }
            else
            {
                DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
                col.HeaderText = headerName;
                DataGridViewTextBoxCell cell = new DataGridViewTextBoxCell();
                col.DataPropertyName = propertyName;
                col.ReadOnly = true;
                return col;
            }
        }
        
        private void dgvPermission_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                DataRow tempRow = dtUserPermissionDetails.Rows[e.RowIndex];
                DataColumn tempCol = dtUserPermissionDetails.Columns[e.ColumnIndex];
                if (!tempCol.ColumnName.Equals("FunctionName"))
                {
                    String status = dgvPermission.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                    if (status.Equals("1"))
                        status = "0";
                    else
                        status = "1";
                    if (tempCol.ColumnName.Equals("PRead"))
                    {
                        dtUserPermissionDetails.Rows[e.RowIndex][e.ColumnIndex] = status;
                        if (status.Equals("0"))
                        {
                            for (int i = 2; i <= 5; i++)
                            {
                                dtUserPermissionDetails.Rows[e.RowIndex][i] = status;
                            }
                        }
                    }
                    else
                    {
                        dtUserPermissionDetails.Rows[e.RowIndex][e.ColumnIndex] = status;
                        if (status.Equals("1"))
                        {
                            dtUserPermissionDetails.Rows[e.RowIndex][1] = status;
                            if (tempRow[2].Equals("1") && tempRow[3].Equals("1") && tempRow[4].Equals("1"))
                            {
                                dtUserPermissionDetails.Rows[e.RowIndex][5] = status;
                            }
                        }
                    }
                    String read = dtUserPermissionDetails.Rows[e.RowIndex]["Pread"].ToString();
                    String write = dtUserPermissionDetails.Rows[e.RowIndex]["PWrite"].ToString();
                    String edit = dtUserPermissionDetails.Rows[e.RowIndex]["PEdit"].ToString();
                    String delete = dtUserPermissionDetails.Rows[e.RowIndex]["PDelete"].ToString();
                    String id = dtUserPermissionDetails.Rows[e.RowIndex]["ID"].ToString();
                    String cmdText = "UPDATE UserPermission SET PRead = '" + read + "', PWrite = '" + write + "', PEdit = '" + edit + "', PDelete = '" + delete + "' WHERE ID = " + id;
                    usersDAO.updateUserPermission(cmdText, row["FirstName"].ToString());
                }
            }
        }
        private void dgvPermission_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if(e.RowIndex > -1)
                dgvPermission.Rows[e.RowIndex].Selected = true;
        }
        private void dgvPermission_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Control control = (Control)sender;
                Point p = control.PointToScreen(new Point(e.X, e.Y));
                cmsPermission.Show(p);
            }
        }
        public void loadAllTabOfTabPermission()
        {
            if (tabControlPermission.TabPages.Count == 0)
            {
                DataTable dtPermissionType = permissionDAO.getAllPermissionType();
                for (int i = 0; i < dtPermissionType.Rows.Count; i++)
                {
                    TabPage tabPage = new TabPage();
                    tabPage.Tag = dtPermissionType.Rows[i]["ID"].ToString();
                    tabPage.Text = dtPermissionType.Rows[i]["TypeName"].ToString();
                    tabControlPermission.TabPages.Add(tabPage);
                }
            }
            tabControlPermission.TabPages[pageIndex].Controls.Clear();
            pageIndex = tabControlPermission.SelectedIndex;
            loadTableUserPermissionDetails();
            tabControlPermission.SelectedTab.Controls.Add(dgvPermission);
            if (dgvPermission.Rows.Count > 0)
                dgvPermission.Rows[0].Selected = true;
        }
        private void tabControlPermission_SelectedIndexChanged(object sender, EventArgs e)
        {
            tabControlPermission.TabPages[pageIndex].Controls.Clear();
            pageIndex = tabControlPermission.SelectedIndex;
            loadTableUserPermissionDetails();
            tabControlPermission.SelectedTab.Controls.Add(dgvPermission);
            if (dgvPermission.Rows.Count > 0)
                dgvPermission.Rows[0].Selected = true;
        }
        private void tabControlUser_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControlUser.SelectedIndex == 0)
                showDetailsUser(row["IDLogin"].ToString());
            else
            {
                loadAllTabOfTabPermission();
            }
        }

        private void allPermissionThisFunctionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            setPermissionByRow("1");
        }

        private void allPermissionViewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            setPermissionByColumn(1, "PRead", "1");
        }
        public void setPermissionByColumn(int index, String colName, String status)
        {
            String cmdText = "";
            for (int i = 0; i < dgvPermission.Rows.Count; i++)
            {
                dtUserPermissionDetails.Rows[i][colName] = status;
                String read = dtUserPermissionDetails.Rows[i]["Pread"].ToString();
                String write = dtUserPermissionDetails.Rows[i]["PWrite"].ToString();
                String edit = dtUserPermissionDetails.Rows[i]["PEdit"].ToString();
                String delete = dtUserPermissionDetails.Rows[i]["PDelete"].ToString();
            }
            usersDAO.updateUserPermissionbyColumn(colName, row["IDLogin"].ToString(), tabControlPermission.SelectedTab.Tag.ToString(), status, row["FirstName"].ToString());
        }
        public void setPermissionByRow(String status)
        {
            String cmdText = "";
            int row = 0;
            if (dgvPermission.SelectedCells.Count > 0)
            {
                row = dgvPermission.SelectedCells[0].RowIndex;
            }
            else if(dgvPermission.SelectedRows.Count > 0)
            {
                row = dgvPermission.Rows.IndexOf(dgvPermission.SelectedRows[0]);
            }
            for (int i = 1; i <= 4; i++)
            {
                dtUserPermissionDetails.Rows[row][i] = status;
            }
            String id = dtUserPermissionDetails.Rows[row]["ID"].ToString();
            cmdText = "UPDATE UserPermission SET PRead = '" + status + "', PWrite = '" + status + "', PEdit = '" + status + "', PDelete = '" + status + "' WHERE ID = " + id;
            usersDAO.updateUserPermission(cmdText, this.row["FirstName"].ToString());
        }
        public void setAllPermissionByStatus(String status)
        {
            String cmdText = "";
            for (int i = 0; i < dgvPermission.Rows.Count; i++)
            {
                dtUserPermissionDetails.Rows[i]["PRead"] = status;
                dtUserPermissionDetails.Rows[i]["PWrite"] = status;
                dtUserPermissionDetails.Rows[i]["PEdit"] = status;
                dtUserPermissionDetails.Rows[i]["PDelete"] = status;
                String id = dtUserPermissionDetails.Rows[i]["ID"].ToString();
            }
            usersDAO.updateUserPermissionbyColumn("", row["IDLogin"].ToString(), tabControlPermission.SelectedTab.Tag.ToString(), status, row["FirstName"].ToString());
        }
        private void noPermissionViewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            setAllPermissionByStatus("0");
        }

        private void allPermissionAddToolStripMenuItem_Click(object sender, EventArgs e)
        {
            setPermissionByColumn(2, "PWrite", "1");
        }

        private void noPermissionAddToolStripMenuItem_Click(object sender, EventArgs e)
        {
            setPermissionByColumn(2, "PWrite", "0");
        }

        private void allToolStripMenuItem_Click(object sender, EventArgs e)
        {
            setPermissionByColumn(3, "PEdit", "1");
        }

        private void noPermissionUpdateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            setPermissionByColumn(3, "PEdit", "0");
        }

        private void allPermissionDeleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            setPermissionByColumn(4, "PDelete", "1");
        }

        private void noPermissionDeleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            setPermissionByColumn(4, "PEdit", "0");
        }

        private void allPermissionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            setAllPermissionByStatus("1");  
        }

        private void thisFunctionHasNoPermissionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            setPermissionByRow("0");
        }
        
    }
}
